package com.jic.market.impl.rest.realtimeprice;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jic.market.entity.GoodsPriceAndStock;
import com.jic.market.entity.PromotionEntity;
import com.jic.market.entity.PromotionMemberGrade;
import com.jic.market.enums.FrontPromotionTypeEnum;
import com.jic.market.impl.rest.realtimeprice.realTimePriceHandler.BaseRealTimePriceHandler;
import com.jic.market.impl.rest.realtimeprice.realTimePriceHandler.BaseRealTimePriceHandlerFactory;
import com.jic.market.mapper.PromotionMemberGradeMapper;
import com.jic.market.model.RealTimePriceContent;
import com.jic.market.request.rest.promotion.PromotionInfoRestRequest;
import com.jic.market.request.rest.realtimeprice.RealTimePriceRequest;
import com.jic.market.response.rest.realtimeprice.RealTimePriceListResponse;
import com.jic.market.response.rest.realtimeprice.RealTimePriceResponse;
import com.jic.market.service.PromotionMemberGradeService;
import com.jic.market.service.rest.promotion.PromotionRestService;
import com.jic.market.service.rest.realtimeprice.RealTimePriceRestService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description: RealTimePriceRestServiceImpl
 * date: 2020/4/10 10:40
 * author: wangys
 * version: 1.0
 */
@Service
@Slf4j
public class RealTimePriceRestServiceImpl implements RealTimePriceRestService {

    @Resource
    private ProductListApi productListApi;

    @Autowired
    PromotionRestService promotionRestService;

    @Autowired
    BaseRealTimePriceHandlerFactory baseRealTimePriceHandlerFactory;

    @Autowired
    private PromotionMemberGradeService promotionMemberGradeService;

    @Autowired
    private PromotionMemberGradeMapper promotionMemberGradeMapper;

    private final static List<Integer> AVAILABLE_PRICE_FRONT_TYPE = Lists.newArrayList(
            FrontPromotionTypeEnum.SINGLELY_DISCOUNT,
            FrontPromotionTypeEnum.SINGLELY_FALL,
            FrontPromotionTypeEnum.SINGLELY_SPECIAL,

            FrontPromotionTypeEnum.SECKILL_SECKILL,

            FrontPromotionTypeEnum.BALANCE_CALCULATION,
            FrontPromotionTypeEnum.BITE_PRICE,

            FrontPromotionTypeEnum.GROUPON

        ).stream().map(FrontPromotionTypeEnum::getCode).collect(Collectors.toList());

    /**
     * 影响价格的促销活动：单一（特价，折扣，直降）/ 秒杀 / 预售(一口价,尾款结算)/拼团（拼团价）
     * @param request
     * @return
     */
    @Override
    public RealTimePriceListResponse getPriceStockList(RealTimePriceRequest request) {
        log.info("getPriceStockList param = {}", JSONObject.toJSONString(request));
        final RealTimePriceListResponse realTimePriceListResponse = new RealTimePriceListResponse();
        List<RealTimePriceResponse> realTimePrices = new ArrayList<>();
        List<ProductStoreInfo> goodsPriceAndStockList = productListApi.queryProductListByThirdProductCodes(new GoodsPageQueryRequest(){{
            setThirdProductCodes(request.getThirdProductCodes());
        }});
        if(CollectionUtils.isNotEmpty(goodsPriceAndStockList)){
            goodsPriceAndStockList.forEach(t->{
                RealTimePriceResponse realTimePriceResponse = new RealTimePriceResponse()
                        .setPromotionCode(request.getPromotionCode())
                        .setMarketPrice(t.getSalePriceWithTax().toString())
                        .setThirdProductCode(t.getCode())
                        .setAvailablePrice(null);
                        //.setStock(t.getStock());

                PromotionEntity promotionEntity = null;
                if(StringUtils.isNotBlank(request.getPromotionCode())){
                    promotionEntity = promotionRestService.promotionDetailByPromotionCode(request.getPromotionCode());
                }else{
                    List<PromotionEntity> promotionEntities = promotionRestService.getPromotionEntities(
                            new PromotionInfoRestRequest()
                                    .setThirdProductCode(t.getCode())
                                    .setProductType(t.getParentId() == null || t.getParentId() == 0L ? 10 : 20)
                    );
                    if(CollectionUtils.isNotEmpty(promotionEntities)){
                        promotionEntity = promotionEntities.stream().filter(x -> {
                            return AVAILABLE_PRICE_FRONT_TYPE.contains(x.getFrontPromType());
                        }).findFirst().orElse(null);
                    }
                    //promotionEntity = promotionRestService.promotionDetailPriority(new PromotionInfoRestRequest().setThirdProductCode(t.getThirdProductCode()));
                }
                if(promotionEntity != null){
                    realTimePriceResponse.setPromotionCode(promotionEntity.getPromotionCode());
                    // 过滤等级 默认true
                    Boolean gradeFlag = Boolean.TRUE;
                    if(gradeFlag){
                        //根据处理器算价格
                        BaseRealTimePriceHandler priceHandler = baseRealTimePriceHandlerFactory.getBaseInfoHandler(promotionEntity.getFrontPromType());
                        log.info("getPriceStockList param = {}, frontPomotionType = {}", JSONObject.toJSONString(request), promotionEntity.getFrontPromType());
                        if(priceHandler != null){
                            priceHandler.accept(new RealTimePriceContent().setGoodsPriceAndStock(new GoodsPriceAndStock(){{
                                setThirdProductCode(t.getCode());
                                setMarketPrice(t.getSalePriceWithTax().toString());
                                setGoodsName(t.getChineseName());
                                setGoodType(t.getParentId() == null || t.getParentId() == 0L ? 10 : 20);
                                setStock(t.getAvailableStock().intValue());
                                setId(t.getId());
                            }}).setPromotionEntity(promotionEntity).setRealTimePriceResponse(realTimePriceResponse));
                        }
                    }

                }
                realTimePrices.add(realTimePriceResponse);
            });
        }
        realTimePriceListResponse.setRealTimePrices(realTimePrices);
        log.info("getPriceStockList param = {}, result = {}", JSONObject.toJSONString(request), JSONObject.toJSONString(realTimePriceListResponse));
        return realTimePriceListResponse;
    }
}
